<?php
/**
 * Created by PhpStorm.
 * Script Name: Mp.php
 * Create: 12/26/22 7:18 PM
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;

use app\common\constant\Common;
use plugin\wechat\app\model\Mp as MpM;
use plugin\wechat\app\service\OpenPlatform as OpenPlatformService;
use plugin\wechat\app\TenantController;
use app\common\service\Tenant as TenantService;
use plugin\wechat\app\service\Common as CommonService;
use plugin\wechat\app\service\Mp as MpService;
use Support\Request;

class Mp extends TenantController
{
    protected bool $insertTenantId = true;
    /**
     * @var MpM
     */
    protected $model;

    public function __construct(){
        parent::__construct();
        $this->model = new MpM();
    }

    public function index(){
        if(request()->isPost()){
            $post_data = input('post.');
            $where = [
                ['company_id', '=', TenantService::getCompanyId()]
            ];
            !empty($post_data['search_key']) && $where[] = ['alias|nick_name', 'like', '%'.$post_data['search_key'].'%'];

            $query = $this->model->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order(['status' => 'desc', 'update_time' => 'desc'])
                    ->select();
            } else {
                $list = [];
            }

            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '搜索词','placeholder' => '微信号或公众号昵称']
        ])
            ->addTopButton('addnew',['href' => url('choose')])
            ->addTableColumn(['title' => '序号', 'type' => 'index', 'minWidth' => 70])
            ->addTableColumn(['title' => '头像', 'field' => 'head_img', 'type' => 'picture','minWidth' => 100])
            ->addTableColumn(['title' => '昵称', 'field' => 'nick_name', 'minWidth' => 100])
            ->addTableColumn(['title' => '微信号', 'field' => 'alias', 'minWidth' => 100])
            ->addTableColumn(['title' => '接入状态', 'field' => 'is_auth', 'type' => 'enum', 'options' => CommonService::platformStatus()])
            ->addTableColumn(['title' => '状态', 'field' => 'status', 'type' => 'switch', 'options' => Common::status()])
            ->addTableColumn(['title' => '操作', 'minWidth' => 130, 'type' => 'toolbar'])
            ->addRightButton('edit', ['href' => url('info', ['id' => '__data_id__']),'title' => '管理设置', 'text' => '管理设置'])
            ->addRightButton('delete');
        return $builder->show();
    }

    /**
     * 管理设置
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function info(){
        $id = input('id', 0);
        if(! $mp_info = $this->model->find($id)){
            return $this->error('数据不存在!');
        }
        $mp_info['url'] = request()->domain() . url('platform/api/index', ['appid' => $mp_info['appid']]);
        $mp_info['type_desc'] = MpService::getTypeDesc($mp_info);
        $assign = ['mp' => $mp_info];
        return $this->show($assign);
    }

    /**
     * 编辑手动接入的公众号
     * @param Request $request
     * @return mixed
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function edit(Request $request){
        if(request()->isPost()){
            $post_data = input('post.');

            $res = $this->validate($post_data,'\\plugin\\wechat\\app\\validate\\Mp.edit');
            if($res !== true){
                return $this->error($res, '', ['token' => token()]);
            }
            return parent::savePost($request, url('info', ['id' => $post_data['id']]), $post_data);
        }
        $id = input('id', 0);
        if(! $mp_info = $this->model->find($id)){
            return $this->error('数据不存在!');
        }
        $builder = new FormBuilder();
        $builder->addFormItem('id', 'hidden', 'id', 'id')
            ->addFormItem('nick_name', 'text', '公众号昵称', '不超过30字', [], 'required maxlength=30')
            ->addFormItem('service_type_info', 'radio', '类型', '类型', MpService::serviceTypes(), 'required')
            ->addFormItem('verify_type_info', 'select', '认证', '认证', MpService::verifyTypes(), 'required')
            ->addFormItem('appid', 'text', 'APPID', '公众号appID', [], 'required')
            ->addFormItem('appsecret', 'text', 'APPSecret', '公众号APPSecret', [], 'required')
            ->addFormItem('refresh_token', 'text', 'Token令牌', '请设置复杂一些', [], 'required minlength=4')
            ->addFormItem('user_name', 'text', '原始ID', '原始ID', [], 'required')
            ->addFormItem('alias', 'text', '微信号', '微信号')
            ->addFormItem('head_img', 'picture_url', '头像', '头像')
            ->addFormItem('qrcode_url', 'picture_url', '二维码', '关注二维码')
            ->addFormItem('verify_file', 'file_to_root', '校验文件', '校验文件')
            ->setFormData($mp_info);
        return $builder->show();
    }

    public function add(Request $request){
        if(request()->isPost()){
            $post_data = input('post.');
            $res = $this->validate($post_data,'\\plugin\\wechat\\app\\validate\\Mp.add');
            if($res !== true){
                return $this->error($res, '', ['token' => token()]);
            }
            $post_data['refresh_token'] = get_rand_char(32);
            $post_data['encodingaeskey'] = get_rand_char(43);
            return parent::savePost($request, '', $post_data);
        }
        $builder = new FormBuilder();
        $builder->addFormItem('nick_name', 'text', '公众号昵称', '不超过30字', [], 'required maxlength=30')
            ->addFormItem('service_type_info', 'radio', '类型', '类型', MpService::serviceTypes(), 'required')
            ->addFormItem('verify_type_info', 'select', '认证', '认证', MpService::verifyTypes(), 'required')
            ->addFormItem('appid', 'text', 'APPID', '公众号appID', [], 'required')
            ->addFormItem('appsecret', 'text', 'APPSecret', '公众号APPSecret', [], 'required')
            ->addFormItem('user_name', 'text', '原始ID', '原始ID', [], 'required')
            ->addFormItem('alias', 'text', '微信号', '微信号')
            ->addFormItem('head_img', 'picture_url', '头像', '头像')
            ->addFormItem('qrcode_url', 'picture_url', '二维码', '关注二维码')
            ->addFormItem('verify_file', 'file_to_root', '校验文件', '校验文件');
        return $builder->show();
    }

    /**
     * 选择添加方式
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function choose(){
        return $this->show();
    }

    /**
     * 公众号授权
     * @author fudaoji<fdj@kuryun.cn>
     */
    public function auth() {
        $redirect_url = request()->domain() . url('authCallback');
        try {
            $url = OpenPlatformService::getOpenPlatform()->getPreAuthorizationUrl($redirect_url);
        }catch (\Exception $e){
            return $this->error("请让站长检查开放平台配置是否正确！");
        }

        $assign = [
            'url' => $url
        ];
        return $this->show($assign);
    }

    /**
     * 公众号授权回调
     * @param Request $request
     * @return \support\Response
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @author fudaoji<fdj@kuryun.cn>
     */
    public function authCallback(Request $request) {
        try {
            // 在用户在授权页授权流程完成后，授权页会自动跳转进入回调URI，并在URL参数中返回授权码和过期时间，如：(https://easywechat.com/callback?auth_code=xxx&expires_in=600)
            $handleAuthorize = OpenPlatformService::getOpenPlatform()->handleAuthorize($request->get('auth_code'));
            $appId = $handleAuthorize['authorization_info']['authorizer_appid'];
            // 获取授权方的帐号基本信息
            $authorizer_info = OpenPlatformService::getOpenPlatform()->getAuthorizer($appId);
            MpService::updateAuthInfo($authorizer_info, TenantService::getCompanyId(), $this->tenantInfo('id'));
            return $this->redirect('/app/wechat/tenant#//app/wechat/tenant/mp/index');
        } catch (\Exception $e){
            dao_log()->error($e->getMessage());
            return $this->error('授权回调处理错误!');
        }
    }
}